package com.snack.shop.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.snack.shop.common.Result;
import com.snack.shop.service.FileManageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@Tag(name = "文件上传")
@RestController
@RequestMapping("/file")
@Slf4j
@RequiredArgsConstructor
public class FileController {

    private final FileManageService fileManageService;

    @Value("${file.upload.path:/tmp/uploads}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:http://localhost:8080/api/uploads}")
    private String urlPrefix;

    @Operation(summary = "上传图片")
    @PostMapping(value = "/upload", produces = "application/json;charset=UTF-8")
    public Result<Map<String, Object>> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "module", required = false, defaultValue = "default") String module) {
        
        if (file.isEmpty()) {
            return Result.failed("文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.failed("只能上传图片文件");
        }

        // 检查文件大小（限制5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            return Result.failed("文件大小不能超过5MB");
        }

        // 清理 module 参数（防止路径注入）
        if (module == null || module.trim().isEmpty()) {
            module = "default";
        }
        module = module.replaceAll("[^a-zA-Z0-9/_-]", "");
        if (module.isEmpty()) {
            module = "default";
        }

        try {
            // 创建基础上传目录
            File baseUploadDir = new File(uploadPath);
            if (!baseUploadDir.isAbsolute()) {
                // 如果是相对路径，转换为绝对路径
                baseUploadDir = new File(System.getProperty("user.dir"), uploadPath);
            }
            
            // 获取日期路径（如：20251104）
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            
            // 创建完整的上传目录：uploads/{module}/{date}
            File uploadDir = new File(baseUploadDir, module + File.separator + dateStr);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    log.error("创建上传目录失败: {}", uploadDir.getAbsolutePath());
                    return Result.failed("创建上传目录失败");
                }
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            String filename = UUID.randomUUID().toString().replace("-", "") + extension;

            // 保存文件
            File destFile = new File(uploadDir, filename);
            log.info("准备保存文件到: {}", destFile.getAbsolutePath());
            file.transferTo(destFile);

            // 构建相对路径用于URL（如：order/takeOut/send/20251104/xxx.jpg）
            String relativePath = module + "/" + dateStr + "/" + filename;
            String fileUrl = urlPrefix + "/" + relativePath;
            
            // 获取上传者ID
            Long uploaderId = null;
            try {
                if (StpUtil.isLogin()) {
                    uploaderId = StpUtil.getLoginIdAsLong();
                }
            } catch (Exception e) {
                log.warn("获取上传者ID失败", e);
            }
            
            // 记录文件上传（临时状态）
            try {
                fileManageService.recordUpload(
                    filename, 
                    relativePath, 
                    fileUrl, 
                    file.getSize(), 
                    module, 
                    dateStr, 
                    uploaderId
                );
            } catch (Exception e) {
                log.error("记录文件上传失败", e);
                // 记录失败不影响上传
            }
            
            // 返回文件信息
            Map<String, Object> result = new HashMap<>();
            result.put("filename", filename);
            result.put("originalName", originalFilename);
            result.put("url", fileUrl);
            result.put("size", file.getSize());
            result.put("module", module);
            result.put("date", dateStr);

            log.info("文件上传成功: {} -> {}", module, relativePath);
            return Result.success(result);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.failed("文件上传失败");
        }
    }
}
